package org.softmed.rest.editor.comps;

import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JTextField;

import org.softmed.rest.editor.EditorUtil;

public class CustomTextField extends JTextField implements KeyListener {
	public static final float secondsToTriggerSave = 2;

	boolean detectChanges = true;
	long lastChange;
	boolean dirty = false;
	SaveThread saveThread = new SaveThread(this);

	public CustomTextField() {
		addKeyListener(this);
	}

	@Override
	public void keyPressed(KeyEvent e) {

		if (!detectChanges)
			return;

		if (e.getKeyCode() == KeyEvent.VK_ENTER)
			return;

		startDelayedSaving();
	}

	public void startDelayedSaving() {
		setBackground(EditorUtil.red);
		dirty = true;
		lastChange = System.currentTimeMillis();

		if (!saveThread.isAlive())
			saveThread.start();
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	public long getLastChange() {
		return lastChange;
	}

	public boolean isDirty() {
		return dirty;
	}

	public void triggerAction() {
		ActionEvent ae = new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
				"SAVE");
		// Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(ae);
		// dispatchEvent(new ActionEvent(this, 1, null));
		ActionListener[] listeners = getActionListeners();
		for (ActionListener actionListener : listeners) {
			actionListener.actionPerformed(ae);
		}
	}

	public void clean() {
		dirty = false;
		setBackground(Color.WHITE);
	}

	public boolean isDetectChanges() {
		return detectChanges;
	}

	public void setDetectChanges(boolean enabled) {
		this.detectChanges = enabled;
	}

}
